<template>
  <div class="container">
    <div class="background-animations">
      <div class="cube"></div>
      <div class="cube"></div>
      <div class="cube"></div>
      <div class="cube"></div>
      <div class="cube"></div>
    </div>
    <div class="login-box animate__animated animate__fadeIn animate__faster">
      <div class="header-section">
        <div class="logo-container">
          <img :src="require('../assets/imgs/logo.png')" alt="CA Logo" class="logo-img"/>
        </div>
        <div class="title-container">
          <div class="title">电脑维修平台</div>
          <div class="subtitle">Professional Computer Repair Service</div>
        </div>
      </div>

      <!-- 登录方式切换 -->
      <div class="login-type-switch">
        <span 
          :class="['switch-item', loginType === 'account' ? 'active' : '']"
          @click="loginType = 'account'"
        >账号密码登录</span>
        <span 
          :class="['switch-item', loginType === 'phone' ? 'active' : '']"
          @click="loginType = 'phone'"
        >手机验证码登录</span>
      </div>

      <el-form :model="form" :rules="rules" ref="formRef">
        <!-- 账号密码登录表单 -->
        <template v-if="loginType === 'account'">
          <el-form-item prop="username">
            <el-input 
              prefix-icon="el-icon-user" 
              placeholder="请输入学号" 
              v-model="form.username"
              class="custom-input">
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input 
              prefix-icon="el-icon-lock" 
              placeholder="请输入密码" 
              show-password  
              v-model="form.password"
              class="custom-input">
            </el-input>
          </el-form-item>
        </template>

        <!-- 手机验证码登录表单 -->
        <template v-if="loginType === 'phone'">
          <el-form-item prop="phoneNumber">
            <el-input 
              prefix-icon="el-icon-mobile-phone" 
              placeholder="请输入手机号码" 
              v-model="form.phoneNumber"
              class="custom-input">
            </el-input>
          </el-form-item>
          <el-form-item prop="code">
            <div class="code-input-container">
              <el-input 
                prefix-icon="el-icon-key" 
                placeholder="请输入验证码" 
                v-model="form.code"
                class="custom-input code-input">
              </el-input>
              <el-button 
                type="primary" 
                :disabled="countdown > 0"
                @click="sendCode"
                class="send-code-btn">
                {{ countdown > 0 ? `${countdown}s后重试` : '获取验证码' }}
              </el-button>
            </div>
          </el-form-item>
        </template>

        <el-form-item>
          <el-select 
            v-model="form.role" 
            placeholder="请选择角色" 
            class="custom-select">
            <el-option label="维修人员" value="REPAIRER"></el-option>
            <el-option label="用户" value="USER"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login-btn" @click="login">
            <span>登 录</span>
          </el-button>
        </el-form-item>
        <div class="register-link">
          <div class="remember-me">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          </div>
          <div>
            还没有账号？请 <router-link to="/register" class="register-text">注册</router-link>
          </div>
        </div>
      </el-form>
    </div>
    <div class="tech-circles">
      <div class="circle"></div>
      <div class="circle"></div>
      <div class="circle"></div>
    </div>
    <div class="tech-lines">
      <div class="line"></div>
      <div class="line"></div>
      <div class="line"></div>
    </div>
    <div class="footer">
      <div class="copyright">
        广软计算机协会 © 2025
        <a href="http://ca.seig.edu.cn" target="_blank" class="footer-link">ca.seig.edu.cn</a>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    // 手机号验证规则
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号码'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'))
      } else {
        callback()
      }
    }

    return {
      loginType: 'account', // 登录方式：account 或 phone
      countdown: 0, // 验证码倒计时
      rememberMe: false,
      form: {
        username: '',
        password: '',
        phoneNumber: '',
        code: '',
        role: 'USER'
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码长度为6位', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 发送验证码
    sendCode() {
      this.$refs['formRef'].validateField('phoneNumber', (valid) => {
        if (!valid) {
          // 使用 params 或 URLSearchParams 发送请求参数
          const params = new URLSearchParams();
          params.append('phoneNumber', String(this.form.phoneNumber));
          
          this.$request.post('/api/sendCode?' + params.toString()).then(res => {
            if (res.code === '200') {
              this.$message.success('验证码发送成功')
              this.startCountdown()
            } else {
              this.$message.error(res.msg || '验证码发送失败')
            }
          }).catch(() => {
            this.$message.error('验证码发送失败，请稍后重试')
          })
        }
      })
    },

    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      const timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(timer)
        }
      }, 1000)
    },

    // 登录方法
    login() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          if (this.loginType === 'account') {
            // 账号密码登录
            this.$request.post('/login', this.form).then(res => {
              if (res.code === '200') {
                let user = res.data
                if (!user.token) {
                  user.token = res.token || `${user.role.toLowerCase()}-token`
                }
                
                // 用户只能以用户身份登录
                if (user.role === "USER") {
                  if (this.form.role === "USER") {
                    localStorage.setItem("xm-user", JSON.stringify(user))
                    this.$router.push('/front/home')
                  } else {
                    this.$message.error('您是用户身份，无法以维修人员身份登录')
                  }
                } 
                // 维修人员可以选择身份登录
                else if (user.role === "REPAIRER") {
                  // 创建一个新的用户对象，根据选择的角色设置
                  const loginUser = {
                    ...user,
                    loginRole: this.form.role // 保存登录时选择的角色
                  }
                  localStorage.setItem("xm-user", JSON.stringify(loginUser))
                  
                  if (this.form.role === "REPAIRER") {
                    this.$router.push('/repair/workbench')
                  } else if (this.form.role === "USER") {
                    this.$router.push('/front/home')
                  }
                  this.$message.success('登录成功')
                }
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.$message.error('登录失败，请检查网络连接')
            })
          } else {
            // 手机验证码登录
            const params = new URLSearchParams();
            params.append('phoneNumber', String(this.form.phoneNumber));
            params.append('code', String(this.form.code));
            params.append('role', this.form.role);

            this.$request.post('/api/login?' + params.toString()).then(res => {
              if (res.code === '200') {
                let user = res.data
                if (!user.token) {
                  user.token = res.token || `${user.role.toLowerCase()}-token`
                }
                
                // 用户只能以用户身份登录
                if (user.role === "USER") {
                  if (this.form.role === "USER") {
                    localStorage.setItem("xm-user", JSON.stringify(user))
                    this.$router.push('/front/home')
                  } else {
                    this.$message.error('您是用户身份，无法以维修人员身份登录')
                  }
                } 
                // 维修人员可以选择身份登录
                else if (user.role === "REPAIRER") {
                  // 创建一个新的用户对象，根据选择的角色设置
                  const loginUser = {
                    ...user,
                    loginRole: this.form.role // 保存登录时选择的角色
                  }
                  localStorage.setItem("xm-user", JSON.stringify(loginUser))
                  
                  if (this.form.role === "REPAIRER") {
                    this.$router.push('/repair/workbench')
                  } else if (this.form.role === "USER") {
                    this.$router.push('/front/home')
                  }
                  this.$message.success('登录成功')
                }
              } else {
                this.$message.error(res.msg || '登录失败')
              }
            }).catch(() => {
              this.$message.error('登录失败，请检查网络连接')
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.container {
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, 
    rgba(23, 36, 64, 0.95), 
    rgba(31, 54, 96, 0.95)
  );
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
}

.container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: 
    radial-gradient(circle at 20% 20%, rgba(41, 98, 255, 0.08) 0%, transparent 50%),
    radial-gradient(circle at 80% 80%, rgba(0, 200, 255, 0.08) 0%, transparent 50%);
  z-index: 0;
  animation: gradientShift 15s ease infinite;
}

@keyframes gradientShift {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

.background-animations {
  position: fixed;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  z-index: 0;
}

.cube {
  position: absolute;
  width: 60px;
  height: 60px;
  background: rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  animation: floatCube 20s linear infinite;
  transform-style: preserve-3d;
}

.cube:nth-child(1) {
  top: 20%;
  left: 20%;
  animation-delay: 0s;
  animation-duration: 15s;
}

.cube:nth-child(2) {
  top: 60%;
  left: 70%;
  width: 90px;
  height: 90px;
  animation-delay: -2s;
  animation-duration: 25s;
}

.cube:nth-child(3) {
  top: 30%;
  left: 80%;
  width: 40px;
  height: 40px;
  animation-delay: -4s;
  animation-duration: 20s;
}

.cube:nth-child(4) {
  top: 70%;
  left: 30%;
  width: 70px;
  height: 70px;
  animation-delay: -6s;
  animation-duration: 22s;
}

.cube:nth-child(5) {
  top: 40%;
  left: 50%;
  width: 50px;
  height: 50px;
  animation-delay: -8s;
  animation-duration: 18s;
}

@keyframes floatCube {
  0% {
    transform: translateY(0) rotateX(0) rotateY(0) translateZ(0);
    opacity: 1;
  }
  50% {
    transform: translateY(-100vh) rotateX(180deg) rotateY(360deg) translateZ(100px);
    opacity: 0.5;
  }
  100% {
    transform: translateY(-200vh) rotateX(360deg) rotateY(720deg) translateZ(0);
    opacity: 0;
  }
}

.login-box {
  width: 420px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.92);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.2),
    inset 0 0 0 1px rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  position: relative;
  z-index: 1;
  transform-style: preserve-3d;
  perspective: 1000px;
  transition: all 0.3s ease;
}

.login-box:hover {
  transform: translateY(-5px) rotateX(5deg);
  box-shadow: 
    0 15px 35px rgba(0, 0, 0, 0.25),
    inset 0 0 0 1px rgba(255, 255, 255, 0.2);
}

.header-section {
  text-align: center;
  margin-bottom: 30px;
  padding: 0 20px;
}

.logo-container {
  text-align: center;
  margin-bottom: 15px;
  position: relative;
  padding: 5px;
  background: transparent;
}

.logo-img {
  width: 180px;
  height: auto;
  object-fit: contain;
  transition: all 0.3s ease;
  filter: drop-shadow(2px 4px 6px rgba(0, 0, 0, 0.1));
}

.logo-img:hover {
  transform: scale(1.02);
  filter: drop-shadow(2px 4px 8px rgba(0, 0, 0, 0.15));
}

.title-container {
  position: relative;
  padding-top: 5px;
}

.title-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 2px;
  background: linear-gradient(90deg, transparent, #ff3333, transparent);
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
  background: linear-gradient(45deg, #ff3333, #cc0000);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1px;
}

.subtitle {
  font-size: 13px;
  color: #666;
  letter-spacing: 1px;
  margin-bottom: 25px;
  font-family: 'Arial', sans-serif;
}

.custom-input :deep(.el-input__inner) {
  height: 45px;
  border-radius: 8px;
  border: 1px solid rgba(64, 158, 255, 0.2);
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.custom-input :deep(.el-input__inner):focus {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.custom-select {
  width: 100%;
}

.custom-select :deep(.el-input__inner) {
  height: 45px;
  border-radius: 8px;
}

.login-btn {
  width: 100%;
  height: 45px;
  border-radius: 8px;
  font-size: 16px;
  background: linear-gradient(45deg, #ff3333, #cc0000);
  border: none;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(255, 255, 255, 0.2),
    transparent
  );
  transition: 0.5s;
}

.login-btn:hover::before {
  left: 100%;
}

.login-btn:hover {
  background: linear-gradient(45deg, #cc0000, #ff3333);
}

.register-link {
  display: flex;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
}

.remember-me {
  flex: 1;
}

.register-text {
  color: #cc0000;
  text-decoration: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.register-text:hover {
  color: #ff3333;
  text-decoration: underline;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #cc0000;
  border-color: #cc0000;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #cc0000;
}

.tech-circles {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
}

.circle {
  position: absolute;
  border: 2px solid rgba(255, 255, 255, 0.03);
  border-radius: 50%;
  box-shadow: 
    0 0 20px rgba(255, 255, 255, 0.03),
    inset 0 0 20px rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
}

.circle:hover {
  border-color: rgba(255, 255, 255, 0.2);
  box-shadow: 
    0 0 30px rgba(255, 255, 255, 0.1),
    inset 0 0 30px rgba(255, 255, 255, 0.1);
}

.circle:nth-child(1) {
  width: 600px;
  height: 600px;
  bottom: -200px;
  right: -200px;
  border-color: rgba(65, 184, 255, 0.05);
  animation: rotate 30s linear infinite;
}

.circle:nth-child(2) {
  width: 400px;
  height: 400px;
  top: -100px;
  left: -100px;
  border-color: rgba(0, 255, 255, 0.05);
  animation: rotate 20s linear infinite reverse;
}

.circle:nth-child(3) {
  width: 200px;
  height: 200px;
  top: 50%;
  left: 50%;
  border-color: rgba(255, 255, 255, 0.05);
  animation: rotate 15s linear infinite;
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.tech-lines {
  position: absolute;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 0;
  opacity: 0.1;
}

.line {
  position: absolute;
  background: linear-gradient(
    90deg, 
    transparent,
    rgba(255, 255, 255, 0.1),
    rgba(64, 158, 255, 0.15),
    rgba(255, 255, 255, 0.1),
    transparent
  );
  height: 2px;
  width: 100%;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.2);
  animation: scan 3s linear infinite;
}

.line:nth-child(1) {
  top: 20%;
  animation-delay: 0s;
}

.line:nth-child(2) {
  top: 50%;
  animation-delay: 1s;
}

.line:nth-child(3) {
  top: 80%;
  animation-delay: 2s;
}

@keyframes scan {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

.footer {
  position: fixed;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  z-index: 1;
}

.copyright {
  font-size: 13px;
  color: rgba(255, 255, 255, 0.7);
  letter-spacing: 0.5px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.footer-link {
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  margin-left: 5px;
  transition: all 0.3s ease;
  position: relative;
}

.footer-link::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 1px;
  background: rgba(255, 255, 255, 0.5);
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.footer-link:hover {
  color: #fff;
}

.footer-link:hover::after {
  transform: scaleX(1);
}

.login-type-switch {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
  gap: 20px;
}

.switch-item {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 4px;
  transition: all 0.3s ease;
  color: #666;
}

.switch-item:hover {
  color: #cc0000;
}

.switch-item.active {
  color: #cc0000;
  font-weight: bold;
  position: relative;
}

.switch-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #cc0000;
  border-radius: 1px;
}

.code-input-container {
  display: flex;
  gap: 10px;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  background: #cc0000;
  border-color: #cc0000;
}

.send-code-btn:hover {
  background: #ff3333;
  border-color: #ff3333;
}

.send-code-btn:disabled {
  background: #ccc;
  border-color: #ccc;
}
</style>